<template>
  <el-dialog
    v-el-drag-dialog
    title="本地打印设置"
    :visible.sync="visible"
    width="700px"
    append-to-body
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp">
      <el-form-item label="本地打印地址:" prop="url" class="block">
        <el-input v-model="temp.url" style="width: 500px;">
          <el-button slot="append" class="append-search" @click="tryConnect">尝试连接</el-button>
        </el-input>
      </el-form-item>
      <el-form-item class="block">
        <div>
          <span style="display: inline-block; width: 525px;">下拉不出打印机列表请点击重新加载</span>
          <el-button type="primary" @click="loadPrinters">重新加载</el-button>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.submit" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  // import { JCJSONTools, tryConnection } from '@/utils/JCCache'

  export default {
    name: 'printSetting',
    data() {
      return {
        visible: false,
        temp: {
          url: ''
        },
        rules: {
          url: [{ required: true, message: '请输入IP及端口号', trigger: 'blur' }]
        },
        printList: []
      }
    },
    created() {
      // window.tools = {
      //   json: new JCJSONTools()
      // }
    },
    methods: {
      open() {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      // 尝试连接
      tryConnect() {
        // this.$refs.dataForm.validate(valid => {
        //   if (!valid) return
        //   window.printer.tryConnection(this.temp.url)
        // })
      },
      // 重新加载
      loadPrinters() {
        // const _this = this
        // window.printer.registListener(function(msg) {
        //   _this.printList = eval(msg)
        // })
        // window.printer.send(window.tools.json.toJson({ cmd: 1 }))
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          this.submit()
        })
      },
      async submit() {
        // await roleUpdate(this.temp)
        this.resolve(this.temp)
        this.visible = false
        this.$notify({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.temp = {
          url: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
